/*
 * MIT License
 *
 * Copyright (c) 2023-present, tangli
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package tony.mybatis.datascope.autoconfigure

import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.boot.context.properties.bind.DefaultValue
import org.springframework.context.annotation.Bean
import tony.core.PROJECT_GROUP
import tony.mybatis.datascope.DataScopeContext
import tony.mybatis.datascope.DefaultDataScopeProvider
import tony.mybatis.datascope.IDataScopeContext
import tony.mybatis.datascope.IDataScopeProvider
import tony.mybatis.datascope.handler.DefaultScopedDataPermissionHandler
import tony.mybatis.datascope.handler.ScopedDataPermissionHandler
import tony.mybatis.datascope.interceptor.ScopedDataPermissionInterceptor
import tony.mybatis.datascope.model.ScopedTable

/**
 * mybatis plus 数据权限自动配置
 * @author tangli
 * @date 2025/09/22 17:07
 */
@ConditionalOnBooleanProperty(prefix = "$PROJECT_GROUP.mybatis-plus.data-scope", name = ["enabled"])
@EnableConfigurationProperties(MybatisPlusDataScopeProperties::class)
@AutoConfiguration
private class MybatisPlusDataScopeAutoConfiguration {
    private val logger = LoggerFactory.getLogger(MybatisPlusDataScopeAutoConfiguration::class.java)

    @ConditionalOnMissingBean(IDataScopeProvider::class)
    @Bean
    private fun dataScopeProvider(properties: MybatisPlusDataScopeProperties): IDataScopeProvider {
        logger.info("Initializing Default Mybatis Plus Data Scope DataScopeProvider.")
        return DefaultDataScopeProvider(
            properties.excludeTables.map { ScopedTable(it) }.toMutableSet(),
            properties.userIdColumn,
            properties.orgIdColumn
        )
    }

    @Bean
    private fun dataScopeContext(dataScopeProvider: IDataScopeProvider): IDataScopeContext =
        DataScopeContext(dataScopeProvider)

    @ConditionalOnBean(IDataScopeProvider::class)
    @Bean
    private fun dataPermissionHandler(): ScopedDataPermissionHandler =
        DefaultScopedDataPermissionHandler()

    @ConditionalOnBean(IDataScopeProvider::class)
    @Bean
    private fun scopedDataPermissionInterceptor(
        scopedDataPermissionHandler: ScopedDataPermissionHandler,
    ): ScopedDataPermissionInterceptor =
        ScopedDataPermissionInterceptor(scopedDataPermissionHandler)
}

@ConfigurationProperties(
    prefix = "$PROJECT_GROUP.mybatis-plus.data-scope",
    ignoreInvalidFields = false,
    ignoreUnknownFields = false
)
public data class MybatisPlusDataScopeProperties(
    /**
     * 是否开启数据权限.
     */
    @DefaultValue("true")
    val enabled: Boolean,
    /**
     * 数据权限处理需要跳过的表. 比如中间表等.
     */
    val excludeTables: Set<String> = mutableSetOf(),
    /**
     * 数据权限列, 用户id默认列名.
     */
    @DefaultValue("creator_id")
    val userIdColumn: String,
    /**
     * 数据权限列, 组织id默认列名.
     */
    @DefaultValue("creator_org_id")
    val orgIdColumn: String,
)
